'''


    UDP client and server


'''
SERVER_PORT = 6666
CLIENT_PORT = 6667
HOST = '127.0.0.1'

import time, socket

class Client:
    def __init__(self, host=HOST, port=CLIENT_PORT):
        self.bufferSize = 1024
        self.addr = (host,port)
        self.srvAddr = None
        self.socket = None
        self.open()
        
    def open(self):
        self.socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        self.socket.bind( self.addr ) 
        self.socket.setblocking(0)
        print "opened"
    
    def connect( self, host=HOST, port=SERVER_PORT ):
        self.serverAddr = (host,port)
        
    def send(self, data ):
        if self.serverAddr is None:
            raise Exception( 'Use Client.connect() First !' )
        self.socket.sendto(data, self.serverAddr)
            
    def recv(self):
        try:
            data, addr = self.socket.recvfrom(self.bufferSize)
            if data:
                print 'from', addr
                return data
        except socket.error, err:
            if err.args[0] not in (10035,35):
                raise
            return None

    def close(self):
        self.socket.close()
       
class Server:
    def __init__(self, host=HOST, port=SERVER_PORT):
        self.addr = (host,port)
        self.bufferSize = 1024
        self.socket = None

    def send(self, data, addr ):
        self.socket.sendto(data,addr)

    def recv(self):
        try:
            data , addr = self.socket.recvfrom(self.bufferSize)
            print 'from', addr
            self.send( 'Ok ('+data+')', addr )
            return data
        except socket.error, err:
            if err.args[0] not in (10035,35):
                raise
            return None
            
    def open(self):
        self.socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        print 'Opening Server on ', self.addr
        self.socket.bind(self.addr)
        self.socket.setblocking(0)

    def close(self):
        self.socket.close()


def TestServer():
    server = Server()
    server.open()
    while 1:
        time.sleep(1)
        print '.',
        d = server.recv()
        if d:
            print ''
            print "SERVER GOT DATA:", d, repr(d)
            if d == "QUIT":
                server.close()
                break

def TestClient():
    client = Client()
    client.connect()
    while True:
        d = client.recv()
        if d is not None:
            print "Server says:", d
        d = raw_input(">>>").strip()
        if not d:
            continue
        if d == 'q':
            break
        print "sending", repr(d)
        client.send(d)
    client.close()
    print "done"

if __name__ == '__main__':
    import sys
    job = {
        'c':TestClient,
        's':TestServer,
    }
    job[sys.argv[1][0]]()